package org.abratuhi.kvngroupware.server;

import java.util.ArrayList;

import org.abratuhi.kvngroupware.model.Brainstorm;
import org.abratuhi.kvngroupware.model.Chatroom;
import org.abratuhi.kvngroupware.model.Team;
import org.abratuhi.kvngroupware.model.User;
import org.abratuhi.kvngroupware.network.Message;
import org.jdom.Element;

public class ServerMPTUA {
	
	KVNGroupwareServer kvnserver;
	
	public  ServerMPTUA(KVNGroupwareServer kvnserver){
		this.kvnserver = kvnserver;
	}
	
	void proceedMessage(Message message){
		Element request = (Element) message.getRoot().getChildren().get(0);
		String type = request.getAttributeValue("type");
		String action = request.getAttributeValue("action");
		
		if(type.equals("application")){
			proceedApplicationMessage(request, type, action);
		}
		else if(type.equals("brainstorm")){
			proceedBrainstormMessage(request, type, action);
		}
		else if(type.equals("chatroom")){
			proceedChatroomMessage(request, type, action);
		}
		
	}
	
	@SuppressWarnings("unchecked")
	void proceedApplicationMessage(Element request, String type, String action){
		if(action.equals("login")){
			String userId = request.getAttributeValue("userId");
			String userPassword = request.getAttributeValue("userPassword");
			
			boolean okLoginPassword = this.kvnserver.getDB().containsLoginPassword(userId, userPassword);
			boolean okLogin = this.kvnserver.getDB().containsLogin(userId);
			User user = this.kvnserver.getUser(userId);
			
			String[] attrNames = new String[]{"type", "action", "userId", "userPassword", "status"};
			String[] attrValues= new String[]{type, action, userId, userPassword, ""};
			String text = new String();
			Element[] content = new Element[0];
			
			Message responseMessage;
			if(okLoginPassword && user == null){
				Element eu = this.kvnserver.getDB().getUser(userId);
				User u = User.fromElement(eu);
				Element et = this.kvnserver.getDB().getTeam(u.getTeamId());
				content = new Element[]{eu ,et};
				attrValues[4] = "ok";
				this.kvnserver.users.add(u);
			}
			else{
				if(user != null){
					attrValues[4] = "used_user";
				}
				else if(okLogin){
					attrValues[4] = "invalid_password";
				}
				else{
					attrValues[4] = "invalid_user";
				}
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("logout")){
			String userId = request.getAttributeValue("userId");
			String userPassword = request.getAttributeValue("userPassword");
			
			boolean okLoginPassword = this.kvnserver.getDB().containsLoginPassword(userId, userPassword);
			boolean okLogin = this.kvnserver.getDB().containsLogin(userId);
			
			String[] attrNames = new String[]{"type", "action", "userId", "userPassword", "status"};
			String[] attrValues= new String[]{type, action, userId, userPassword, ""};
			String text = new String();
			Element[] content = new Element[0];
			Message responseMessage;
			
			if(okLoginPassword){
				attrValues[4] = "ok";
				this.kvnserver.removeUser(userId);
			}
			else if(okLogin){
				attrValues[4] = "invalid_password";
			}
			else{
				attrValues[4] = "invalid_user";
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("create_user")){
			Element newUserElement = request.getChild("user");
			newUserElement.detach();
			User newUser = User.fromElement(newUserElement);
			
			boolean containsLogin = this.kvnserver.getDB().containsLogin(newUser.getId());
			
			String[] attrNames = new String[]{"type", "action", "status"};
			String[] attrValues= new String[]{type, action, ""};
			String text = new String();
			Element[] content = new Element[]{newUserElement};
			Message responseMessage;
			
			if(!containsLogin){
				this.kvnserver.getDB().addUser(newUserElement);
				
				attrValues[2] = "ok";
			}
			else{
				attrValues[2] = "user_found";
			}

			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("create_team")){
			Element newTeamElement = request.getChild("team");
			newTeamElement.detach();
			Team newTeam = Team.fromElement(newTeamElement);
			
			boolean containsTeam = this.kvnserver.getDB().containsTeam(newTeam.getId());
			
			String[] attrNames = new String[]{"type", "action", "status"};
			String[] attrValues= new String[]{type, action, ""};
			String text = new String();
			Element[] content = new Element[]{newTeamElement};
			Message responseMessage;
			
			if(!containsTeam){
				kvnserver.getDB().addTeam(newTeamElement);
				
				attrValues[2] = "ok";
			}
			else{
				attrValues[2] = "team_found";
			}

			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("get_team")){
			String team = request.getAttributeValue("teamId");
			String league = request.getAttributeValue("seasonId");
			String season = request.getAttributeValue("leagueId"); 
			
			String[] attrNames = new String[]{"type", "action", "teamId",  "seasonId", "leagueId","status"};
			String[] attrValues= new String[]{type, action, team, season, league, "ok"};
			String text = new String();
			Element[] content = kvnserver.getDB().getTeams();
			Message responseMessage;
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("get_joke")){
			String userId = request.getAttributeValue("userId");
			String teamId = request.getAttributeValue("teamId");
			String leagueId = request.getAttributeValue("seasonId");
			String seasonId = request.getAttributeValue("leagueId");
			
			String[] attrNames = new String[]{"type", "action", "userId", "teamId",  "seasonId", "leagueId","status"};
			String[] attrValues= new String[]{type, action, userId, teamId, seasonId, leagueId, "ok"};
			String text = new String();
			Element[] content = kvnserver.getDB().getJokes(userId, teamId);
			Message responseMessage;
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("create_joke")){
			String[] attrNames = new String[]{"type", "action", "status"};
			String[] attrValues= new String[]{type, action, "ok"};
			String text = new String();
			Element[] content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
			Message responseMessage;
			
			for(int i=0; i<content.length; i++){
				kvnserver.db.addJoke(content[i]);
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("update_joke")){

			String[] attrNames = new String[]{"type", "action", "status"};
			String[] attrValues= new String[]{type, action, "ok"};
			String text = new String();
			Element[] content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
			Message responseMessage;
			
			for(int i=0; i<content.length; i++){
				kvnserver.db.updateJoke(content[i]);
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("get_scenario")){
			String leagueId = request.getAttributeValue("leagueId");
			String seasonId = request.getAttributeValue("seasonId");
			String teamId = request.getAttributeValue("teamId");
			String scenarioId = request.getAttributeValue("scenarioId");
			
			String[] attrNames = new String[]{"type", "action", "scenarioId", "teamId",  "seasonId", "leagueId","status"};
			String[] attrValues= new String[]{type, action, scenarioId, teamId, seasonId, leagueId, "ok"};
			String text = new String();
			Element[] content = kvnserver.getDB().getScenarios(teamId);
			Message responseMessage;
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("create_scenario")){
			String[] attrNames = new String[]{"type", "action", "status"};
			String[] attrValues= new String[]{type, action, "ok"};
			String text = new String();
			Element[] content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
			Message responseMessage;
			
			for(int i=0; i<content.length; i++){
				kvnserver.getDB().addScenario(content[i]);
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("update_scenario")){
			String[] attrNames = new String[]{"type", "action", "status"};
			String[] attrValues= new String[]{type, action, "ok"};
			String text = new String();
			Element[] content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
			Message responseMessage;
			
			for(int i=0; i<content.length; i++){
				kvnserver.db.updateJoke(content[i]);
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("add_scenario_joke")){
			String scenarioId = request.getAttributeValue("scenarioId");
			
			String[] attrNames = new String[]{"type", "action", "scenarioId", "status"};
			String[] attrValues= new String[]{type, action, scenarioId, "ok"};
			String text = new String();
			Element[] content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
			Message responseMessage;
			
			for(int i=0; i<content.length; i++){
				kvnserver.getDB().addScenarioJoke(scenarioId, content[i]);
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("remove_scenario_joke")){
			String scenarioId = request.getAttributeValue("scenarioId");
			
			String[] attrNames = new String[]{"type", "action", "scenarioId", "status"};
			String[] attrValues= new String[]{type, action, scenarioId, "ok"};
			String text = new String();
			Element[] content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
			Message responseMessage;
			
			for(int i=0; i<content.length; i++){
				kvnserver.getDB().removeScenarioJoke(scenarioId, content[i]);
			}
			
			responseMessage = createMessage(attrNames, attrValues, text, content);
			this.kvnserver.sendMessage(responseMessage);
		}
		else if(action.equals("up_scenario_joke")){	// TODO
			
		}
		else if(action.equals("down_scenario_joke")){// TODO
			
		}
		else if(action.equals("get_brainstorm")){	// TODO
			
		}
	}
	
	void proceedBrainstormMessage(Element request, String type, String action){
		String brainstormId = request.getAttributeValue("brainstormId");
		String userId = request.getAttributeValue("userId");
		String teamId = request.getAttributeValue("teamId");
		String theme = request.getAttributeValue("theme");
		
		String[] attrNames = new String[]{"type", "action", "brainstormId",  "userId", "teamId", "theme", "status"};
		String[] attrValues= new String[]{type, action, brainstormId, userId, teamId, theme, ""};
		String text = new String();
		Element[] content = new Element[0];
		Message responseMessage;
		
		if(action.equals("create")){
			Brainstorm brainstorm = kvnserver.getBrainstorm(brainstormId);
			if(brainstorm == null){
				brainstorm = new Brainstorm(brainstormId, teamId, theme);
				this.kvnserver.brainstorms.add(brainstorm);
				
				attrValues[6] = "ok";
			}
			else{
				attrValues[6] = "brainstormId_found";
			}
		}
		else if(action.equals("get")){
			ArrayList<Element> eBrainstorms = new ArrayList<Element>();
			for(int i=0; i<this.kvnserver.brainstorms.size(); i++){
				Element eBrainstorm = this.kvnserver.brainstorms.get(i).toElement();
				eBrainstorms.add(eBrainstorm);
			}
			attrValues[6] = "ok";
			content = eBrainstorms.toArray(new Element[eBrainstorms.size()]);
		}
		else if(action.equals("delete")){
			Brainstorm brainstorm = kvnserver.getBrainstorm(brainstormId);
			if(brainstorm != null){
				this.kvnserver.brainstorms.remove(brainstorm);
				
				attrValues[6] = "ok";
			}
			else{
				attrValues[6] = "brainstormId_notfound";
			}
		}
		else if(action.equals("join")){
			User user = kvnserver.getUser(userId);
			Brainstorm brainstorm = kvnserver.getBrainstorm(brainstormId);
			if(brainstorm != null && user != null && !brainstorm.containsMember(user)){
				brainstorm.addMember(user, "", "idle");
				
				attrValues[6] = "ok";
			}
			else if(brainstorm == null){
				attrValues[6] = "brainstormId_notfound";
			}
			else if(user == null){
				attrValues[6] = "userId_notfound";
			}
			else if(brainstorm.containsMember(user)){
				attrValues[6] = "userId_found";
			}
		}
		else if(action.equals("leave")){
			User user = kvnserver.getUser(userId);
			Brainstorm brainstorm = kvnserver.getBrainstorm(brainstormId);
			
			if(brainstorm != null && user != null){
				brainstorm.removeMember(userId);
				
				attrValues[6] = "ok";
			}
			else if(brainstorm == null){
				attrValues[6] = "brainstormId_notfound";
			}
			else if(user == null){
				attrValues[6] = "userId_notfound";
			}
			
			if(brainstorm != null && user != null && brainstorm.getMembers().size() == 0){
				this.kvnserver.getDB().addBrainstorm(brainstorm.toBackupElement());
				this.kvnserver.removeBrainstorm(brainstormId);
				//Message message = createMessage(attrNames, new String[]{type, "delete", brainstormId, "system", "ok"}, text, content);
				//this.kvnserver.sendMessage(message);
			}
		}
		else if(action.equals("commit")){
			User user = kvnserver.getUser(userId);
			Brainstorm brainstorm = kvnserver.getBrainstorm(brainstormId);
			if(brainstorm != null && user != null){
				brainstorm.commitSheet(userId, request.getText());
				text = request.getText();
				
				attrValues[6] = "ok";
			}
			else if(brainstorm == null){
				attrValues[6] = "brainstormId_notfound";
			}
			else if(user == null){
				attrValues[6] = "userId_notfound";
			}
		}
		else if(action.equals("switch")){
			User user = kvnserver.getUser(userId);
			Brainstorm brainstorm = kvnserver.getBrainstorm(brainstormId);
			if(brainstorm != null && user != null){
				brainstorm.switchSheets();
				
				attrValues[6] = "ok";
			}
			else if(brainstorm == null){
				attrValues[6] = "brainstormId_notfound";
			}
			else if(user == null){
				attrValues[6] = "userId_notfound";
			}
		}
		
		responseMessage = createMessage(attrNames, attrValues, text, content);
		this.kvnserver.sendMessage(responseMessage);
	}
	
	void proceedChatroomMessage(Element request, String type, String action){
		String chatroomId = request.getAttributeValue("chatroomId");
		String userId = request.getAttributeValue("userId");
		
		String[] attrNames = new String[]{"type", "action", "chatroomId",  "userId", "status"};
		String[] attrValues= new String[]{type, action, chatroomId, userId, ""};
		String text = new String();
		Element[] content = new Element[0];
		Message responseMessage;
		
		if(action.equals("create")){
			Chatroom chatroom = kvnserver.getChatroom(chatroomId);
			if(chatroom == null){
				chatroom = new Chatroom(chatroomId);
				this.kvnserver.chatrooms.add(chatroom);
				
				attrValues[4] = "ok";
			}
			else{
				attrValues[4] = "chatroomId_found";
			}
		}
		else if(action.equals("get")){
			ArrayList<Element> eChatrooms = new ArrayList<Element>();
			for(int i=0; i<this.kvnserver.chatrooms.size(); i++){
				Element eChatroom = this.kvnserver.chatrooms.get(i).toElement();
				eChatrooms.add(eChatroom);
			}
			attrValues[4] = "ok";
			content = eChatrooms.toArray(new Element[eChatrooms.size()]);
		}
		else if(action.equals("delete")){
			Chatroom chatroom = kvnserver.getChatroom(chatroomId);
			if(chatroom != null){
				this.kvnserver.chatrooms.remove(chatroom);
				
				attrValues[4] = "ok";
			}
			else{
				attrValues[4] = "chatroomId_notfound";
			}
		}
		else if(action.equals("join")){
			User user = kvnserver.getUser(userId);
			Chatroom chatroom = kvnserver.getChatroom(chatroomId);
			if(chatroom != null && user != null && !chatroom.containsMember(user)){
				chatroom.addMember(user);
				
				attrValues[4] = "ok";
			}
			else if(chatroom == null){
				attrValues[4] = "chatroomId_notfound";
			}
			else if(user == null){
				attrValues[4] = "userId_notfound";
			}
			else if(chatroom.containsMember(user)){
				attrValues[4] = "userId_found";
			}
		}
		else if(action.equals("leave")){
			User user = kvnserver.getUser(userId);
			Chatroom chatroom = kvnserver.getChatroom(chatroomId);
			
			if(chatroom != null && user != null){
				chatroom.removeMember(userId);
				
				attrValues[4] = "ok";
			}
			else if(chatroom == null){
				attrValues[4] = "chatroomId_notfound";
			}
			else if(user == null){
				attrValues[4] = "userId_notfound";
			}
			
			if(chatroom != null && user != null && chatroom.getMembers().size() == 0){
				this.kvnserver.removeChatroom(chatroomId);
				//Message message = createMessage(attrNames, new String[]{type, "delete", brainstormId, "system", "ok"}, text, content);
				//this.kvnserver.sendMessage(message);
			}
		}
		else if(action.equals("send")){
			User user = kvnserver.getUser(userId);
			Chatroom chatroom = kvnserver.getChatroom(chatroomId);
			if(chatroom != null && user != null){
				text = request.getText();
				
				attrValues[4] = "ok";
			}
			else if(chatroom == null){
				attrValues[4] = "chatroomId_notfound";
			}
			else if(user == null){
				attrValues[4] = "userId_notfound";
			}
		}
		
		responseMessage = createMessage(attrNames, attrValues, text, content);
		this.kvnserver.sendMessage(responseMessage);
	}
	
	
	Message createMessage(String[] attrNames, String[] attrValues, String text, Element[] content){
		Element message = new Element("message");
		message.setAttribute("application", "kvngroupware");
		
		Element response = new Element("response");
		
		response.setText(text);
		
		if(attrNames!=null && attrValues!=null && attrNames.length==attrValues.length){
		for(int i=0; i<attrNames.length; i++){
			response.setAttribute(attrNames[i], attrValues[i]);
		}
		}
		
		if(content!=null){
		for(int i=0; i<content.length; i++){
			response.addContent(content[i]);
		}
		}
		
		message.addContent(response);
		
		return new Message(message);
	}
	
}
